package com.rwind.dynamic.controller;

import com.rwind.dynamic.ApiRequestHandler;
import org.springframework.http.MediaType;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.Objects;

public class DynamicRegisterController {
    @Resource
    RequestMappingHandlerMapping requestMappingHandlerMapping;

    ApiRequestHandler handler = new ApiRequestHandler();

    /**
     * 注册接口
     * @param requestMethod 请求方法
     * @param url 接口URL
     */
    public void register(String requestMethod, String url) {
        RequestMappingInfo mappingInfo = RequestMappingInfo.paths(url)
                .methods(RequestMethod.valueOf(requestMethod))
                .produces(MediaType.APPLICATION_JSON_VALUE)
                //.options(requestMappingHandlerMapping.)
                .build();
        Method method = ReflectionUtils.findMethod(ApiRequestHandler.class, "handler",
                HttpServletRequest.class, HttpServletResponse.class,
                Map.class, Map.class, Map.class);
        Objects.requireNonNull(method, "反射获取方法为空");
        requestMappingHandlerMapping.registerMapping(mappingInfo, handler, method);
    }

    /**
     * 注销接口
     * @param requestMethod 请求方法
     * @param url 接口URL
     */
    public void unRegister(String requestMethod, String url) {
        RequestMappingInfo mappingInfo = RequestMappingInfo.paths(url)
                .methods(RequestMethod.valueOf(requestMethod))
                .produces(MediaType.APPLICATION_JSON_VALUE)
                //.options(requestMappingHandlerMapping.getBuilderConfiguration())
                .build();
        requestMappingHandlerMapping.unregisterMapping(mappingInfo);
    }


}
